const db = require('../config/db');
const { sendError } = require('../utils/response');

module.exports = {
  // 创建订单
  async createOrder(userId, addressId, cartItems) {
    const conn = await db.getConnection();
    try {
      await conn.beginTransaction();

      // 1. 检查地址是否属于用户
      const [addresses] = await conn.execute(
        'SELECT * FROM addresses WHERE id = ? AND user_id = ?',
        [addressId, userId]
      );

      if (addresses.length === 0) {
        throw new Error('地址不存在或不属于当前用户');
      }

      const address = addresses[0];

      // 2. 检查购物车商品并计算总价
      let totalAmount = 0;
      const orderItems = [];

      for (const item of cartItems) {
        const [products] = await conn.execute(
          'SELECT id, price, stock FROM products WHERE id = ? AND status = "active" FOR UPDATE',
          [item.product_id]
        );

        if (products.length === 0) {
          throw new Error(`商品ID ${item.product_id} 不存在或已下架`);
        }

        const product = products[0];

        if (product.stock < item.quantity) {
          throw new Error(`商品 ${product.id} 库存不足`);
        }

        totalAmount += product.price * item.quantity;
        orderItems.push({
          product_id: product.id,
          quantity: item.quantity,
          price: product.price
        });
      }

      if (orderItems.length === 0) {
        throw new Error('购物车为空');
      }

      // 3. 生成订单号 (格式: 年月日时分秒+随机4位)
      const orderNumber = `${new Date().toISOString().replace(/[-:T.Z]/g, '').slice(0, 14)}${Math.floor(1000 + Math.random() * 9000)}`;

      // 4. 创建订单
      const [orderResult] = await conn.execute(
        'INSERT INTO orders (user_id, order_number, total_amount, address_id) VALUES (?, ?, ?, ?)',
        [userId, orderNumber, totalAmount, addressId]
      );

      const orderId = orderResult.insertId;

      // 5. 添加订单项并减少库存
      for (const item of orderItems) {
        await conn.execute(
          'INSERT INTO order_items (order_id, product_id, quantity, price) VALUES (?, ?, ?, ?)',
          [orderId, item.product_id, item.quantity, item.price]
        );

        await conn.execute(
          'UPDATE products SET stock = stock - ? WHERE id = ?',
          [item.quantity, item.product_id]
        );
      }

      // 6. 清空购物车
      await conn.execute('DELETE FROM cart_items WHERE user_id = ?', [userId]);

      await conn.commit();

      return orderId;
    } catch (err) {
      await conn.rollback();
      throw err;
    } finally {
      conn.release();
    }
  },

  // 获取用户订单列表
  async getOrdersByUserId(userId, page = 1, limit = 10) {
    const offset = (page - 1) * limit;

    const [orders] = await db.execute(
      'SELECT o.*, a.receiver_name, a.receiver_phone, ' +
      'CONCAT(a.province, a.city, a.district, a.detail_address) as address ' +
      'FROM orders o JOIN addresses a ON o.address_id = a.id ' +
      'WHERE o.user_id = ? ORDER BY o.created_at DESC LIMIT ? OFFSET ?',
      [userId, limit, offset]
    );

    // 获取总数用于分页
    const [total] = await db.execute(
      'SELECT COUNT(*) as count FROM orders WHERE user_id = ?',
      [userId]
    );

    return {
      orders,
      pagination: {
        total: total[0].count,
        page,
        limit,
        totalPages: Math.ceil(total[0].count / limit)
      }
    };
  },

  // 获取订单详情
  async getOrderById(userId, orderId) {
    const [orders] = await db.execute(
      'SELECT o.*, a.receiver_name, a.receiver_phone, ' +
      'CONCAT(a.province, a.city, a.district, a.detail_address) as address ' +
      'FROM orders o JOIN addresses a ON o.address_id = a.id ' +
      'WHERE o.id = ? AND o.user_id = ?',
      [orderId, userId]
    );

    if (orders.length === 0) {
      throw new Error('订单不存在');
    }

    const order = orders[0];

    const [items] = await db.execute(
      'SELECT oi.*, p.name, p.images FROM order_items oi ' +
      'JOIN products p ON oi.product_id = p.id ' +
      'WHERE oi.order_id = ?',
      [orderId]
    );

    order.items = items;
    return order;
  },

  // 更新订单状态
  async updateOrderStatus(userId, orderId, status) {
    const validStatuses = ['pending', 'paid', 'shipped', 'delivered', 'cancelled'];

    if (!validStatuses.includes(status)) {
      throw new Error('无效的订单状态');
    }

    if (status === 'paid') {

    }
    let order = {}
    // 检查订单是否属于用户
    let [orders] = []
    if(status === "paid"||status === "pending") {
       [orders] = await db.execute(
        'SELECT id, status FROM orders WHERE id =? AND user_id =?',
        [orderId, userId]
      );
    }
    [orders] = await db.execute(
      'SELECT id, status FROM orders WHERE id = ? AND user_id = ?',
      [orderId, userId]
    );

    if (status === "shipped" || status === "delivered") {
       [orders] = await db.execute(
        'SELECT id, status FROM orders WHERE id = ? ',
        [orderId]
      );
    }

    if (orders.length === 0) {
      throw new Error('订单不存在');
    }

    order = orders[0];

    // 状态流转验证
    if (status === 'cancelled' && order.status !== 'pending') {
      throw new Error('只有待支付的订单可以取消');
    }

    if (status === 'paid' && order.status !== 'pending') {
      throw new Error('订单已支付');
    }

    if (status === 'shipped' && order.status !== 'paid') {
      throw new Error('只有已支付的订单可以发货');
    }

    if (status === 'delivered' && order.status !== 'shipped') {
      throw new Error('只有已发货的订单可以确认收货');
    }

    const [result] = await db.execute(
      'UPDATE orders SET status = ? WHERE id = ?',
      [status, orderId]
    );

    return result.affectedRows > 0;
  },

  // 商家获取订单列表
  async getOrdersForMerchant(merchantId, page = 1, limit = 10) {
    const offset = (page - 1) * limit;

    const [orders] = await db.execute(
      'SELECT DISTINCT o.*, a.receiver_name, a.receiver_phone FROM orders o ' +
      'JOIN order_items oi ON o.id = oi.order_id ' +
      'JOIN products p ON oi.product_id = p.id ' +
      'JOIN addresses a ON o.address_id = a.id ' +
      'WHERE p.merchant_id = ? ORDER BY o.created_at DESC LIMIT ? OFFSET ?',
      [merchantId, limit, offset]
    );

    // 获取总数用于分页
    const [total] = await db.execute(
      'SELECT COUNT(DISTINCT o.id) as count FROM orders o ' +
      'JOIN order_items oi ON o.id = oi.order_id ' +
      'JOIN products p ON oi.product_id = p.id ' +
      'WHERE p.merchant_id = ?',
      [merchantId]
    );

    return {
      orders,
      pagination: {
        total: total[0].count,
        page,
        limit,
        totalPages: Math.ceil(total[0].count / limit)
      }
    };
  },

  // 商家获取订单详情
  async getOrderForMerchant(merchantId, orderId) {
    const [orders] = await db.execute(
      'SELECT DISTINCT o.*, a.receiver_name, a.receiver_phone, ' +
      'CONCAT(a.province, a.city, a.district, a.detail_address) as address ' +
      'FROM orders o ' +
      'JOIN order_items oi ON o.id = oi.order_id ' +
      'JOIN products p ON oi.product_id = p.id ' +
      'JOIN addresses a ON o.address_id = a.id ' +
      'WHERE o.id = ? AND p.merchant_id = ?',
      [orderId, merchantId]
    );

    console.log('查询结果:', orders.length);

    if (orders.length === 0) {
      throw new Error('订单不存在');
    }

    const order = orders[0];



    const [items] = await db.execute(
      'SELECT oi.*, p.name, p.images FROM order_items oi ' +
      'JOIN products p ON oi.product_id = p.id ' +
      'WHERE oi.order_id = ? AND p.merchant_id = ?',
      [orderId, merchantId]
    );

    order.items = items;
    return order;
  }
};